from selenium import webdriver
from PIL import Image
#from aip import AipOcr
from baidu import api

# 验证码的获取和处理
def get_captcha():
    # 获取验证码图片
    url = 'http://wgpc.wzsafety.gov.cn/login_qygl.htm'
    browser.get(url)
    png = browser.find_element_by_class_name('ValidataImage')
    png.screenshot('capt.png')  # 将图片截屏并保存
    # 处理验证码
    img = Image.open('capt.png')
    img = img.convert('L')  # P模式转换为L模式(灰度模式默认阈值127)
    count = 160  # 设定阈值
    table = []
    for i in range(256):
        if i < count:
            table.append(0)
        else:
            table.append(1)

    img = img.point(table, '1')
    img.save('captcha.png')  # 保存处理后的验证码


# 验证码的识别
def discern_captcha():
    # 识别码
    APP_ID = '*** '
    API_KEY = '***'
    SECRET_KEY = '***'
    # 初始化对象
    #client = AipOcr(APP_ID, API_KEY, SECRET_KEY)
    client =api(APP_ID, API_KEY, SECRET_KEY)
    # 读取图片
    def get_file_content(file_path):
        with open(file_path, 'rb') as f:
            return f.read()

    image = get_file_content('captcha.png')
    # 定义参数变量
    options = {'language_type': 'ENG', }  # 识别语言类型，默认为'CHN_ENG'中英文混合
    #  调用通用文字识别
    result = client.basicGeneral(image, options)  # 高精度接口 basicAccurate
    for word in result['words_result']:
        captcha = (word['words'])

        print('识别结果：' + captcha)

        return captcha


# 登录网页
def login(captcha):
    browser.find_element_by_id('uid_51').send_keys('***')  # 找到账号框并输入账号
    browser.find_element_by_id('password_51').send_keys('***')  # 找到密码框并输入密码
    browser.find_element_by_id('validataimage_50').send_keys(captcha)  # 找到验证码框并输入验证码
    browser.find_element_by_id('b_denglu_51').click()  # 找到登陆按钮并点击


def get_file():
    browser.find_element_by_xpath('/html/body/header/div/nav/ul/li[6]/a').click()  # 找到文件按钮并点击


if __name__ == '__main__':
    browser = webdriver.Firefox()  # 实例化对象

    get_captcha()
    captcha = discern_captcha()
    login(captcha)
    get_file()